import sys
import os.path

#设计实现一个学生管理系统

students = []

def menu():
    print("     1、新增学生    ")
    print("     2、显示学生    ")
    print("     3、查找学生    ")
    print("     4、删除学生    ")
    print("     0、退出程序    ")
    choice = input("   请输入你要执行的选项: ")
    return choice


def save():
    with open("record.txt", "w", encoding="utf-8") as f:
        for s in students:
            f.write(f"{s['studentID']}\t{s['name']}\t{s['gender']}\t{s['classID']}\n")
        print(f"存档成功！共存储了{len(students)}条记录！")


def lode():
    if not os.path.exists('record.txt'):
        return
    global students
    students = []
    with open("record.txt", "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            token = line.split("\t")
            if len(token) != 4:
                print(f"当前格式存在问题! line={line}")
                continue
            student = {
                "studentID": token[0],
                "name": token[1],
                "gender": token[2],
                "classID": token[3],
            }
            students.append(student)
    print(f"读档成功！ 共读到 {len(students)} 条记录！")


def main():
    #进入系统
    print('+------------------------------------------+')
    print('|----------    欢迎来到学生管理系统    ------- |')
    print('+------------------------------------------+')

    lode()
    while True:
        choice = menu()
        if choice == '1':
            #新增学生
            insert()
        elif choice == '2':
            #显示学生
            show()
        elif choice == '3':
            #查找学生
            find()
        elif choice == '4':
            #删除学生
            delect()
        elif choice == '0':
            break
        else:
            print("输入错误，请重新输入！")

def insert():
    print("[新增学生] 开始！")
    global students
    studentID = input("请输入学生学号:")
    name = input("请输入学生姓名:")
    gender = input("请输入学生性别:")
    if gender not in ('男','女'):
        print("输入错误！")
        sys.exit(0)
    classID = input("请输入学生班级:")
    student = {
        'name': name,
        'gender': gender,
        'classID': classID,
        'studentID': studentID
    }
    students.append(student)
    save()
    print("[新增学生] 完毕！")


def show():
    print("[显示学生] 开始！")
    for s in students:
        print(f'[{s['studentID']}]\t{s["name"]}\t{s["gender"]}\t{s["classID"]}')
    print(f'[显示学生] 完毕！共有{len(students)}个学生信息！')


def find():
    print("[查找学生] 开始！")
    #按照学生姓名进行查找
    count = 0
    name = input("请输入你要查找的学生姓名:")
    for s in students:
        if name == s["name"]:
            print(f'[{s['studentID']}]\t{s["name"]}\t{s["gender"]}\t{s["classID"]}')
            count += 1
    print(f"[查找学生] 完毕！共有 {count} 个学生")


def delect():
    print("[删除学生] 开始！")
    #按照学生学号进行删除学生信息
    studentID = input("请输入学生学号:")
    for s in students:
        if s["studentID"] == studentID:
            print(f"删除 {s['name']} 同学的信息！")
            students.remove(s)

    save()
    print("[删除学生] 完毕！")



main()
